package com.woniu.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.gateway.dto.ManageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;

import static com.woniu.common.constant.FinanceConstant.RequestFilter.USER_REQ_PATH;
import static com.woniu.common.constant.FinanceConstant.RequestFilter.USER_ROLE;
import static com.woniu.common.constant.FinanceConstant.WhiteListRedis.WHITE_LIST_KEY;

/**
 * packageName com.woniu.gateway.filter
 *
 * @author zxyang3636
 * @version JDK 8
 * @className RequestFilter
 * @date 2024/8/13
 * @description TODO
 */
@Order(2)
//@Component
@Slf4j
public class RequestFilter implements GlobalFilter {
    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 是否白名单路径
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = String.valueOf(request.getPath());

        ArrayList<String> whiteList = new ArrayList<>();
        whiteList.add("/token");
        whiteList.add("/register");
        whiteList.add("/queryProductDetail");
        whiteList.add("/queryGoods");
        whiteList.add("/login");
        whiteList.add("/isLogin");
        whiteList.add("/faceReg");
        whiteList.add("/faceLog");
        for (String s : whiteList) {
            if (requestPath.contains(s)) {
                return chain.filter(exchange);
            }
        }

        // 解析token
        String token = request.getHeaders().getFirst("token");
        Object user = JWTUtil.parseToken(token).getPayload("zyManage");
        ManageDTO manageDTO = JSONObject.parseObject(String.valueOf(user), ManageDTO.class);
        String userId = manageDTO.getId();

        if (userId.equals("1")){
            return chain.filter(exchange);
        }

        // redis中获取当前用户的所有角色
        String roleKey = USER_ROLE + userId; //redis中角色key
        Flux<String> roleIds = redisTemplate.opsForHash().keys(roleKey).cast(String.class);  //keys根据大key获取小key
        // redis获取该角色能够访问的所有路径
        Flux<String> reqPaths = roleIds.flatMap(roleId -> {
            String reqPathKey = USER_REQ_PATH + roleId;
            return redisTemplate.opsForHash().keys(reqPathKey).cast(String.class);
        });
        // 1.判断是否白名单 2.判断请求路径是否在该角色的 请求路径中
        return redisTemplate.opsForHash().hasKey(WHITE_LIST_KEY, requestPath).flatMap(b -> {
            if (b) {
                log.info("白名单放行路径：{}", requestPath);
                return chain.filter(exchange);
            }
            return reqPaths.hasElement(requestPath).flatMap(flag -> {
                if (!flag) {
                    return getMono(exchange);
                }
                return chain.filter(exchange);
            });
        });
    }

    private static Mono<Void> getMono(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }
}
